const http = require('http');
const socketIo = require('socket.io');
const mongoose = require('mongoose');
const app = require('./app');
const dotenv = require('dotenv');

// 加载环境变量
dotenv.config();

// 创建HTTP服务器
const server = http.createServer(app);

// 设置Socket.IO
const io = socketIo(server, {
  cors: {
    origin: process.env.FRONTEND_URL || 'http://localhost:3000',
    methods: ['GET', 'POST'],
    credentials: true
  }
});

// 数据库连接
const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/scratch_cn', {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log('MongoDB连接成功');
  } catch (error) {
    console.error('MongoDB连接失败:', error.message);
    process.exit(1);
  }
};

// 连接数据库
connectDB();

// Socket.IO连接处理
io.on('connection', (socket) => {
  console.log('新的WebSocket连接:', socket.id);

  // 处理用户加入房间
  socket.on('joinRoom', (roomId) => {
    socket.join(roomId);
    console.log(`用户 ${socket.id} 加入房间 ${roomId}`);
  });

  // 处理用户离开房间
  socket.on('leaveRoom', (roomId) => {
    socket.leave(roomId);
    console.log(`用户 ${socket.id} 离开房间 ${roomId}`);
  });

  // 处理代码更新
  socket.on('codeUpdate', (data) => {
    // 将代码更新广播给房间内的其他用户
    socket.to(data.roomId).emit('codeUpdate', data);
  });

  // 处理断开连接
  socket.on('disconnect', () => {
    console.log('WebSocket连接断开:', socket.id);
  });
});

// 设置端口
const PORT = process.env.PORT || 5000;

// 启动服务器
server.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});